package com.whj.wkpt.controller;

import com.whj.wkpt.entity.User;
import com.whj.wkpt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@ModelAttribute("user") User user,
                               Model model) {
        // 检查用户名是否已存在
        if (userService.existsByUsername(user.getUsername())) {
            model.addAttribute("usernameError", "用户名已存在");
            return "register";
        }

        // 检查邮箱是否已存在
        if (userService.existsByEmail(user.getEmail())) {
            model.addAttribute("emailError", "邮箱已被注册");
            return "register";
        }

        // 设置默认角色为freelancer
        if (user.getRole() == null || user.getRole().isEmpty()) {
            user.setRole("freelancer");
        }
        
        // 对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        userService.createUser(user);
        return "redirect:/login?registerSuccess";
    }

    @GetMapping("/login")
    public String showLoginForm(@RequestParam(value = "error", required = false) String error,
                                @RequestParam(value = "logout", required = false) String logout,
                                @RequestParam(value = "registerSuccess", required = false) String registerSuccess,
                                Model model) {
        if (error != null) {
            model.addAttribute("error", "用户名或密码错误");
        }
        if (logout != null) {
            model.addAttribute("message", "您已成功退出登录");
        }
        if (registerSuccess != null) {
            model.addAttribute("message", "注册成功，请登录");
        }
        return "login";
    }

    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        model.addAttribute("username", username);
        return "dashboard";
    }

    @GetMapping("/profile")
    public String showProfile(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.findByUsername(username).orElse(new User());
        model.addAttribute("user", user);
        return "profile";
    }

    @PostMapping("/profile")
    public String updateProfile(@ModelAttribute("user") User user, Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(new User());
        
        // 更新用户信息（不包括用户名和密码）
        currentUser.setEmail(user.getEmail());
        currentUser.setPhone(user.getPhone());
        userService.updateUser(currentUser);
        
        model.addAttribute("user", currentUser);
        model.addAttribute("updateSuccess", "个人信息更新成功");
        return "profile";
    }
}